import { Table, Button, Input, message, Popconfirm } from 'antd';
import { useRef } from 'react';
import {} from '@ant-design/icons';
import useGetData from 'hooks/useGetData';
import { getBgs, delBg, addBg } from 'api/material';
import ImageView, { ImageViewMethods } from 'components/ImageView';
import { dateFormat } from '@/utils/funcs';
import Prompt, { PromptMethods } from 'components/Prompt';

const MAX_SIZE = 2;
const BASE_IMAGE = import.meta.env.VITE_IMG_URL as string;
export default function () {
	const { filterInfo, page, viewInfo, setFilterInfo, setPageIndex, setViewInfo, getData }: any = useGetData(
		getBgs,
		{
			name: '',
		},
		'materials'
	);

	const promptRef = useRef<PromptMethods>(null);
	const previewRef = useRef<ImageViewMethods>();
	return (
		<div>
			<Prompt innerRef={promptRef} />
			<ImageView innerRef={previewRef} />
			<div className=' flex items-center mb-4'>
				<p>名称：</p>
				<Input
					style={{ width: 260 }}
					value={filterInfo.name}
					onChange={({ target: { value: name } }) => {
						setFilterInfo({ ...filterInfo, name }); // deep clone
					}}
					placeholder='关键词'
				/>
				<Button
					className=' ml-auto mr-1'
					onClick={() => {
						const upInput = document.createElement('input');
						upInput.type = 'file';
						upInput.click();
						upInput.onchange = async ({ target: e }: any) => {
							const file = e.files[0];
							const { size, type } = file;
							if (size > MAX_SIZE * 1024 * 1024) return message.warning(`支持上传的最大文件为${MAX_SIZE}M`);
							if (!['image/png', 'image/jpeg'].includes(type)) return message.warning(`仅支持上传jpg格式或者png格式`);
							const formData = new FormData();
							let name;
							promptRef.current?.prompt({
								title: '上传素材',
								content: [
									{
										label: '请输入素材名称',
										name: 'name',
										rules: [{ required: true, message: '请输入素材名称' }],
										type: 'text',
									},
								],
								onOk: async ({ name }: any) => {
									if (!name) return;
									formData.append('file', file);
									formData.append('name', name);
									const { id, content } = await addBg({ data: formData, type: 1 });
									previewRef.current!.preview({ src: URL.createObjectURL(file) });
									message.success('上传成功');
									setViewInfo({ ...viewInfo, list: [{ id, content, name }, ...viewInfo.list] });
									upInput.remove();
								},
							});
						};
					}}>
					上传
				</Button>
			</div>
			<Table
				dataSource={viewInfo.list || []}
				rowKey={({ id }) => `row-${id}`}
				columns={[
					{ title: '编号', dataIndex: 'id', width: 60 },
					{ title: '名称', dataIndex: 'name', width: 140 },
					{
						title: '链接',
						dataIndex: 'content',
						width: 160,
						render: (v) => (
							<p
								onClick={() => {
									window.open(BASE_IMAGE + v);
								}}
								className=' truncate hover:text-blue-300 transition-300 cursor-pointer '>
								{v}
							</p>
						),
					},
					{ title: '创建时间', dataIndex: 'createtime', width: 160, render: (v) => dateFormat(v) },
					{
						title: '操作',
						fixed: 'right',
						width: 150,
						render: (e: any, { id, content }: { id: number; content: string }, index: number) => (
							<div className=' gap-1 flex'>
								<Button
									key={'view-' + id}
									onClick={() => {
										console.log(BASE_IMAGE + content);
										previewRef.current!.preview({ src: BASE_IMAGE + content });
									}}>
									预览
								</Button>
								<Popconfirm
									placement='topLeft'
									title='警告'
									description={`删除该素材，正在使用中的素材不受影响！`}
									onConfirm={async () => {
										await delBg(id);
										const { list } = viewInfo;
										list.splice(index, 1);
										setViewInfo({ ...viewInfo, list: [...list] });
										message.success('删除成功');
									}}
									okText='Yes'
									cancelText='No'
									key={'del-' + id}>
									<Button>删除</Button>
								</Popconfirm>
							</div>
						),
					},
				]}
				scroll={{ y: 'initial' }}
				pagination={{
					total: viewInfo.total,
					showTotal: (total: number) => `共 ${total} 项`,
					showSizeChanger: false,
					position: ['bottomLeft'],
					current: page,
					defaultPageSize: 15,
					onChange: (e: any) => setPageIndex(e),
				}}
			/>
		</div>
	);
}
